import {
  Utils
} from '@/utils/utils.js';
import Vue from 'vue';
import md5 from 'blueimp-md5';
import {
  asyncRouterMap,
  constantRouterMap
} from '@/router';
import router from '@/router/index';

const _import = require('@/router/_import_' + process.env.NODE_ENV);

function RecursionInitcomponent(routemap) {
  routemap.forEach((route) => {
    if (route.componentpath) {
      route.component = _import(route.componentpath);
    }
    if (route.children && route.children.length > 0) {
      RecursionInitcomponent(route.children);
    }
  });
};

const userauth = {
  state: {
    userInfo: {},
    authRouters: [],
    allRouters: [],
    authRouterPaths: [],
    token: ''
  },
  mutations: {
    // 设置userInfo
    SET_USER_INFO: (state, info) => {
      state.userInfo = info;
    },
    // 设置本地路由
    SET_ROUTERS: (state) => {
      // 从服务器获取的合法路由信息
      let remoteroutes = state.userInfo.remoteroutes;
      RecursionInitcomponent(remoteroutes);
      state.authRouters = remoteroutes;
      state.allRouters = constantRouterMap.concat(remoteroutes);
      state.authRouterPaths = state.userInfo.authroutepaths;
      router.addRoutes(remoteroutes); // 动态添加可访问路由表
    },
    // 设置Token
    SET_TOKEN: (state, token) => {
      state.token = token;
    }
  },

  actions: {
    // 邮箱登录
    LoginByEmail({
      commit
    }, userInfo) {
      userInfo.password = md5('zillionoss' + userInfo.password);
      return Vue.axios.post('/Jwt/GetJwt/ZilLionOss', userInfo).then((response) => {
        if (response.data.isSuccess) {
          Utils.SetLocalData('zillionossjwt', response.data.token);
          commit('SET_TOKEN', response.data.token);
        } else {
          Utils.RemoveLocalData('zillionossjwt');
          commit('SET_TOKEN', '');
        }
      });
    },
    // 获取用户信息
    GetLoginUser({
      commit
    }) {
      return Vue.axios.get('/Oss/Auth/GetLoginUser').then((response) => {
        if (response.data.isSuccess) {
          const data = response.data.user;
          commit('SET_USER_INFO', data);
          commit('SET_ROUTERS', data);
        }
      });
    },
    // 强制重置本地路由到云端
    ForceResetRoutes({
      commit
    }) {
      console.log(asyncRouterMap);
      return Vue.axios.post('/Oss/Auth/ForceResetRoutes', asyncRouterMap);
    },
    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        Utils.RemoveLocalData('zillionossjwt');
        commit('SET_TOKEN', '');
        resolve();
      });
    }
  }
};

export default userauth;
